package cn.edu.jxau.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import cn.edu.jxau.domain.user;
import cn.itcast.jdbc.TxQueryRunner;

public class UserDao {
	private QueryRunner qr = new TxQueryRunner();

	/**
	 * 添加用户数据进数据库
	 * 
	 * @param user
	 */
	public void add(user user) {

		String sql = "insert into user(username,password,mail,phonenumber) values(?,?,?,?)";
		Object[] params = { user.getUsername(), user.getPassword(), user.getMail(), user.getPhonenumber() };

		try {
			qr.update(sql, params);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据用户名查找用户信息 返回值：user对象
	 */
	public user findByUsername(String username) {
		String sql = "select * from user where username=?";

		try {
			return qr.query(sql, new BeanHandler<user>(user.class), username);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}

	/**
	 * 根据用户名更新用户密码
	 */

	public void updata(String username, String password) {
		String sql = "update user set password=? where username=?";
		Object[] param = { password, username };

		try {
			qr.update(sql, param);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}

	public void updataState(String username, String state) {
		// TODO Auto-generated method stub
		String sql = "update userinfo set state=? where username=?";
		Object[] param = { "1", username };
		try {
			qr.update(sql, param);
		} catch (SQLException e) {
			throw new RuntimeException();
		}
	}

	/*
	 * 根据用户名删除用户
	 */
	public void delByUsername(String username) {
		String sql = "delete from user where username=?";
		try {
			qr.update(sql, username);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
